<?php


namespace app\cms\middleware;

use app\community\oauth2\Repository\AccessTokenRepository;
use iflow\App;
use iflow\middleware\Middleware;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Middleware\ResourceServerMiddleware;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
use League\OAuth2\Server\ResourceServer;
use Psr\Http\Message\ResponseInterface;

#[Middleware]
class Oauth2
{

    protected AccessTokenRepositoryInterface $accessTokenRepository;
    protected ResourceServer $resourceServer;
    protected ResourceServerMiddleware $resourceServerMiddleware;
    protected array $config = [];

    public function handle(App $app, $next)
    {
        $config = config('oauth') ?: [];
        // 当未开启 OAUTH2服务时
        if (!$config['enable']) return $next($app);

        $this->config = $config['oauth2'][$config['default']] ?? [];

        // 执行验证
        return $this->start($app, $next);
    }

    public function start(App $app, $next)
    {
        $this->accessTokenRepository = new AccessTokenRepository();
        $this->resourceServer = new ResourceServer(
            $this->accessTokenRepository,
            new CryptKey($this->config['openSslCert']['public'], keyPermissionsCheck: false)
        );
        $this->resourceServerMiddleware = new ResourceServerMiddleware($this->resourceServer);
        $response = $this->resourceServerMiddleware -> __invoke(
            request() -> getServerRequestPsr7(),
            response() -> getResponsePsr7(),
            function ($request, $response) {
            }
        );

        if ($response instanceof ResponseInterface) {
            return $response;
        }

        return $next($app);
    }

}